﻿using System;
using System.Configuration;
using System.Data;
using System.Linq;
using Microsoft.Win32;

namespace DataService
{
    public enum DatabaseTypes
    {
        MS_SQL = 0,
        ORACLE = 1
    }

    public class DataServiceUtil
    {
        public static string UnknownDbType = "Unknown Database type !";

        public static string GetConnStr(string pConnectionStringName)
        {
            string connectionString = string.Empty;
            string cnnStrRegKeyName = CnnStrRegKeyName;
            bool readFromRegistry = !string.IsNullOrEmpty(cnnStrRegKeyName) ? true : false;

            if (readFromRegistry)
                connectionString = ReadRegistryValue(pConnectionStringName, cnnStrRegKeyName);
            else
                connectionString = ConfigurationManager.ConnectionStrings[pConnectionStringName].ConnectionString;

            return connectionString;
        }

        private static string ReadRegistryValue(string pValueName, string pCnnStrRegKeyName)
        {
            string keyValue = Convert.ToString(Registry.GetValue(pCnnStrRegKeyName, pValueName, string.Empty));
            if (!string.IsNullOrEmpty(keyValue)) keyValue = keyValue.Decrypt();

            return keyValue;
        }

        private static bool IsProduction
        {
            get
            {
                if (!ConfigurationManager.AppSettings.AllKeys.Contains("IsProd")) return true;

                AppSettingsReader appReader = new AppSettingsReader();
                return Convert.ToBoolean(appReader.GetValue("IsProd", typeof(bool)));
            }
        }

        private static string CnnStrRegKeyName
        {
            get
            {
                AppSettingsReader appReader = new AppSettingsReader();
                string regKeyName = Convert.ToString(appReader.GetValue("ConnectionStringsRegistryKeyName", typeof(string)));
                return regKeyName;
            }
        }

        public static DatabaseTypes DatabaseType()
        {
            string dbType = "DbType".ReadAppSetting<string>("MS_SQL");
            switch (dbType)
            {
                case "MS_SQL": return DatabaseTypes.MS_SQL;
                case "ORACLE": return DatabaseTypes.ORACLE;
                default: return DatabaseTypes.MS_SQL;
            }
        }

        public static void SetTableName(DataTable pDataTable)
        {
            if (String.IsNullOrEmpty(pDataTable.TableName))
                pDataTable.TableName = "Table1";
        }

        public static void SetTableName(DataSet pDataSet)
        {
            int i = 0;
            foreach (DataTable table in pDataSet.Tables)
            {
                i++;
                if (String.IsNullOrEmpty(table.TableName))
                    table.TableName = string.Format("Table{0}", i.ToString());
            }
        }
    }
}
